<template>
  <template v-if="modelValue"
    ><div ref="applyInfoHeaderRef" class="applyInfo-header">
      <el-scrollbar
        ref="elScrollRef"
        :max-height="420"
        style="margin-right: -9%; padding-right: 9%"
      >
        <div class="applyInfo-header__title clearfix">
          <img
            class="headerTit-avatar"
            :src="user.userInfo.avatar"
            @click="openModal(user.userInfo.avatar)"
            alt=""
          />
          <div class="headerTit-property">
            <span class="property-nickName">{{ user.userInfo.nickName }}</span>
            <span class="property__gender">
              <SvgIcon v-if="user.userInfo.sex === '男'" icon-class="man" />
              <SvgIcon v-else icon-class="woman" />
            </span>
            <p class="property__age">年龄：{{ user.userInfo.age }}</p>
            <p class="property__account">账号：{{ userId }}</p>
            <p class="property__address" v-if="user.userInfo.address">
              地区：{{ user.userInfo.address }}
            </p>
          </div>
          <el-input
            style="margin: 10px 0 20px"
            :disabled="true"
            type="textarea"
            :value="`@${user.userInfo.nickName}：${user.otherProto.applyLan}`"
            resize="none"
            :autosize="{ minRows: 4, maxRows: 4 }"
          />
        </div>
        <el-form :label-width="54" style="padding-left: 5%">
          <el-form-item label="备注名">
            <el-input
              v-model.trim="agreeProperties.remark"
              maxlength="8"
              :disabled="user.otherProto.isLoadingRefuse || user.otherProto.isLoading"
              @blur="remarkBlur(agreeProperties.remark)"
              @keypress.enter.prevent="($refs.tagRef as any).focus()"
            />
          </el-form-item>
          <el-form-item label="分组">
            <el-input
              ref="tagRef"
              :disabled="user.otherProto.isLoadingRefuse || user.otherProto.isLoading"
              v-model.trim="agreeProperties.group"
              maxlength="16"
              placeholder="设置分组"
            />
          </el-form-item>
        </el-form>
        <div class="applyInfo-header__tag" v-if="tags.size">
          <el-tag
            v-for="[name, { type }] in tags"
            :key="name"
            :type="type"
            class="tag-item"
            @click="selectTag(name)"
          >
            {{ name }}
          </el-tag>
          <SvgIcon
            v-if="groups.maxPage > 1 && groups.currentPage < groups.maxPage"
            icon-class="more"
            popper-class="more-group"
            @click="requestNextGroup(++groups.currentPage)"
          />
        </div>
        <div style="padding-left: 5%">
          <moments-permission
            :disabled="user.otherProto.isLoadingRefuse || user.otherProto.isLoading"
            v-model="permission"
          ></moments-permission>
        </div>
      </el-scrollbar>
    </div>
    <div class="applyInfo-footer">
      <el-button
        class="applyInfo-footer__refuse"
        :disabled="user.otherProto.isLoadingRefuse || user.otherProto.isLoading"
        @click="refuseApply"
        >拒绝</el-button
      >
      <el-button
        class="applyInfo-footer__agree"
        type="primary"
        :disabled="user.otherProto.isLoading || user.otherProto.isLoadingRefuse"
        :loading="user.otherProto.isLoading"
        @click="agreeApply"
        ><template #loading><Loading /></template>同意</el-button
      >
    </div>
    <Modal v-model="showModal"> <img class="img-browser" :src="imgSrc" alt="" /> </Modal
  ></template>
</template>

<script lang="ts" setup>
import { ref, watchEffect, nextTick } from "vue";
import Modal from "@/components/ui-components/modal.vue";
import momentsPermission from "@/components/momentsPermission.vue";
import handleToTags from "@/plugins/handleToTags";
import { useUserPinia } from "@/pinia/user";
import { useFriendPinia } from "@/pinia/friend";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import type { ElScrollbar } from "element-plus";

const props = defineProps<{
  user: {
    userInfo: Omit<User, "remark" | "userId">;
    otherProto: {
      applyLan: string;
      isLoading: boolean;
      time: number;
      isLoadingRefuse: boolean;
    };
  };
  // 是否显示该组件
  modelValue: boolean;
  userId: string;
}>();
const emits = defineEmits<{
  (e: "update:modelValue", show: boolean): void;
}>();

const userStore = useUserPinia();
const friendStore = useFriendPinia();
const { user: usr } = storeToRefs(userStore);
const { groups } = storeToRefs(friendStore);

/**
 * 当前用户查看的图片的url
 */
const imgSrc = ref<string>("");
/**
 * 是否显示模态框
 */
const showModal = ref<boolean>(false);
// 浏览图片时打开模态框
const openModal: (url: string) => void = (url: string): void => {
  imgSrc.value = url;
  showModal.value = true;
};

/**
 * 朋友圈权限
 */
const permission = ref<Permission>({
  // 是否允许别人看自己的动态
  disabledOtherLook: false,
  // 是否允许自己看别人的动态
  disabledSelfLook: false,
});

/**
 * 同意申请的属性(如：备注名，标签等)
 */
const agreeProperties = ref<{
  remark: string;
  group: string;
}>({
  remark: "",
  group: "",
});

watchEffect(() => {
  if (props.user.userInfo.nickName)
    agreeProperties.value.remark = props.user.userInfo.nickName;
});

// 备注名输入框失焦时如果备注名此时为空字符串的话则自动设置为该申请用户的昵称
const remarkBlur = (value: string) =>
  value || (agreeProperties.value.remark = props.user.userInfo.nickName);

// 处理过后的标签数据
const tags = ref<Map<string, { type: "" | "success" | "info" | "warning" | "danger" }>>(
  new Map(handleToTags(groups.value.value))
);

// 选择分组标签
const selectTag = (name: string) => {
  if (!props.user.otherProto.isLoading && !props.user.otherProto.isLoadingRefuse)
    agreeProperties.value.group = name;
};

// 是否正在请求下一页的分组情况
const isRequestNextPageGroup = ref<boolean>(false);
const elScrollRef = ref<typeof ElScrollbar>();
const applyInfoHeaderRef = ref<HTMLDivElement>(document.createElement("div"));

// 请求下一页的分组情况
const requestNextGroup = (page: number) => {
  if (!isRequestNextPageGroup.value) {
    isRequestNextPageGroup.value = true;
    friendStore
      .getUserGroups({ page })
      .then((payload: { code: number; value: string[] }) => {
        isRequestNextPageGroup.value = false;
        if (payload.code === 1) {
          const newTagData = handleToTags(payload.value);
          for (const [key, { type }] of newTagData.entries())
            tags.value.set(key, { type });
          const ele = applyInfoHeaderRef.value.getElementsByClassName(
            "el-scrollbar__wrap"
          )[0] as HTMLElement;
          nextTick(() => {
            const top: number = ele.scrollHeight - ele.offsetHeight;
            top > 0 && nextTick(() => elScrollRef.value!.setScrollTop(top));
          });
        } else
          ElMessage({
            type: "error",
            message: "加载失败",
            duration: 1500,
          });
      })
      .catch(() => {
        isRequestNextPageGroup.value = false;
        ElMessage({
          type: "error",
          message: "加载失败",
          duration: 1500,
        });
      });
  }
};

// 拒绝申请
const refuseApply = () => {
  props.user.otherProto.isLoadingRefuse = true;
  props.user.otherProto.isLoading = true;
  userStore
    .isAgreeApply({
      selfId: usr.value.userId,
      otherId: props.userId,
      isAgree: false,
    })
    .then((code: number) => {
      props.user.otherProto.isLoading = false;
      props.user.otherProto.isLoadingRefuse = false;
      if (code === 1) {
        permission.value.disabledOtherLook = false;
        permission.value.disabledSelfLook = false;
        emits("update:modelValue", false);
        ElMessage({
          type: "success",
          message: "拒绝成功",
          duration: 1500,
        });
      } else
        ElMessage({
          type: "error",
          message: "拒绝失败",
          duration: 1500,
        });
    })
    .catch(() => {
      props.user.otherProto.isLoading = false;
      props.user.otherProto.isLoadingRefuse = false;
      ElMessage({
        type: "error",
        message: "拒绝失败",
        duration: 1500,
      });
    });
};
// 同意申请
const agreeApply = () => {
  props.user.otherProto.isLoading = true;
  userStore
    .isAgreeApply(
      {
        isAgree: true,
        selfId: usr.value.userId,
        otherId: props.userId,
        friendProperty: {
          ...permission.value,
          ...agreeProperties.value,
        },
      },
      { ...props.user.userInfo }
    )
    .then((code: number) => {
      props.user.otherProto.isLoading = false;
      if (code === 1) {
        permission.value.disabledOtherLook = false;
        permission.value.disabledSelfLook = false;
        emits("update:modelValue", false);
        ElMessage({
          type: "success",
          message: "添加成功",
          duration: 1500,
        });
      } else
        ElMessage({
          type: "error",
          message: "添加失败",
          duration: 1500,
        });
    })
    .catch(() => {
      props.user.otherProto.isLoading = false;
      ElMessage({
        type: "error",
        message: "添加失败",
        duration: 1500,
      });
    });
};
</script>

<style lang="scss" scoped>
.applyInfo {
  &-header {
    padding: 20px 10% 0 15%;
    max-height: 420px;
    margin-left: -15%;

    &__title {
      padding-left: 15%;

      .headerTit {
        &-avatar {
          @include setWidHei(80px, 80px);
          border-radius: 8px;
          object-fit: cover;
          cursor: pointer;
          float: left;
        }

        &-property {
          float: left;
          margin-left: 7%;
          max-width: calc(100% - 7% - 80px);

          .property {
            &-nickName {
              word-break: break-all;
              font: {
                weight: 600;
                size: 17px;
              }
            }

            &__gender {
              color: #3d93ef;
              margin-left: 10px;
              font-size: 20px;
            }

            &__address {
              word-break: break-all;
            }

            &__account,
            &__address,
            &__age {
              margin: 3px 0 3px;
              font-size: 14px;
              color: #626161ca;
            }
          }
        }
      }
    }

    &__tag {
      margin-bottom: 6px;
      padding-left: 15%;

      .tag-item {
        cursor: pointer;
        margin: 0 8px 8px 0;
      }

      .more-group {
        font-size: 23px;
        cursor: pointer;
        margin-left: 6px;
        vertical-align: middle;
      }
    }
  }

  &-footer {
    height: 60px;
    position: relative;

    %thame {
      position: absolute;
      width: 30%;
      top: 50%;
      transform: translateY(-50%);
    }

    &__refuse {
      left: 10%;
      @extend %thame;
    }

    &__agree {
      right: 10%;
      @extend %thame;
    }
  }
}
</style>
